package cn.zhixiangsingle.impl.gasBase;


import cn.zhixiangsingle.config.DynamicDataSourceContextHolder;
import cn.zhixiangsingle.dao.gasBase.GasBaseMapper;
import cn.zhixiangsingle.dao.site.SiteMapper;
import cn.zhixiangsingle.entity.base.IsEmptyUtils;
import cn.zhixiangsingle.entity.base.site.SiteData;
import cn.zhixiangsingle.entity.base.site.vo.SiteVO;
import cn.zhixiangsingle.entity.gas.GasBase.dto.GasBaseDTO;
import cn.zhixiangsingle.impl.additiveBase.AdditiveBaseServiceImpl;
import cn.zhixiangsingle.pagination.MyStartEndUtil;
import cn.zhixiangsingle.service.gasBase.GasBaseService;
import cn.zhixiangsingle.web.responsive.IStatusMessage;
import cn.zhixiangsingle.web.responsive.ResultBean;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zn
 * @description 瓦斯泄漏基础信息业务
 * @date 2019/11/14 15:23
 * @Copyright: 2019 www.zhixiangyun.net Inc. All rights reserved.
 * 注意：本内容仅限于浙江智飨科技内部传阅，禁止外泄以及用于其他的商业目
 */


@Service(version = "1.0.0", interfaceClass = GasBaseService.class)
public class GasBaseServiceImpl implements GasBaseService {

    private static final Logger logger = LoggerFactory
            .getLogger(AdditiveBaseServiceImpl.class);
    @Autowired
    private SiteMapper siteMapper;
    @Autowired
    private GasBaseMapper gasBaseMapper;

    /**
     * @描述
     * @参数 [gasBaseDTO]
     * @返回值 cn.zhixiangsingle.web.responsive.ResultBean
     * @创建人 zn
     * @创建时间 2019/11/16
     * @修改人和其它信息
     */

    @Override
    public ResultBean findGasBaseList(GasBaseDTO gasBaseDTO) throws Exception {
        ResultBean resultBean = new ResultBean();
        if (IsEmptyUtils.isEmpty(gasBaseDTO.getPage())) {
            gasBaseDTO.setPage(1);
        }
        if (IsEmptyUtils.isEmpty(gasBaseDTO.getLimit())) {
            gasBaseDTO.setLimit(10);
        }
        Integer page = gasBaseDTO.getPage();
        Integer limit = gasBaseDTO.getLimit();
        StringBuffer stringBufferJson = new StringBuffer();
        InputStream stream = getClass().getClassLoader().getResourceAsStream("json/siteData.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            stringBufferJson.append(line);
        }
        JSONObject jobj = JSON.parseObject(stringBufferJson.toString());

        List<Map<String, Object>> mainLPLs = Lists.newArrayList();
        Integer total = 0;
        int startNum = (page - 1) * limit;
        int endNum = startNum + limit;
        ArrayList<Integer> totalAll = Lists.newArrayList();
        gasBaseDTO.setId(-1);

        gasBaseDTO.setTime("t");
        if(IsEmptyUtils.isEmpty(gasBaseDTO.getGasArea())){
            gasBaseDTO.setGasArea("g");
        }

        if(IsEmptyUtils.isEmpty(gasBaseDTO.getGasSensor())){
            gasBaseDTO.setGasSensor("g");
        }
        if(IsEmptyUtils.isEmpty(gasBaseDTO.getGasVal())){
            gasBaseDTO.setGasVal("g");
        }
        if(IsEmptyUtils.isEmpty(gasBaseDTO.getGasYhVal())){
            gasBaseDTO.setGasYhVal("g");
        }
        if(IsEmptyUtils.isEmpty(gasBaseDTO.getTime())){
            gasBaseDTO.setTime("t");
        }

        if (!IsEmptyUtils.isEmpty(gasBaseDTO.getSdIds())) {
            String[] sdIds = gasBaseDTO.getSdIds().split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for (String sdId : sdIds) {
                gasBaseDTO.setSdId(Integer.parseInt(sdId));
                String dataSourceName = "";
                SiteData siteData = null;
                if (!IsEmptyUtils.isEmpty(jobj.get(sdId))) {
                    siteData = JSON.parseObject(jobj.get(sdId).toString(), SiteData.class);
                }
                gasBaseDTO.setPicturePrefix(siteData.getPicturePrefix());
                if (!IsEmptyUtils.isEmpty(siteData)) {
                    dataSourceName = siteData.getDateSourceName();
                }
                if (!IsEmptyUtils.isEmpty(dataSourceName)) {
                    if (IsEmptyUtils.isEmpty(stringBuffer)) {
                        stringBuffer.append(sdId);
                    } else {
                        stringBuffer.append("," + sdId);
                    }
                    logger.info("--" + dataSourceName + "--");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);
                    Integer totalStatus = gasBaseMapper.findGasBaseTotal(gasBaseDTO);
                    total = total + totalStatus;
                    totalAll.add(totalStatus);
                }
            }
            ArrayList<ArrayList<Integer>> startEndNums = MyStartEndUtil.getStartEndArray(totalAll, startNum, endNum);
            String[] sourceNames = stringBuffer.toString().split(",");
            for (int i = 0; i < startEndNums.size(); i++) {
                gasBaseDTO.setSdId(Integer.parseInt(sourceNames[i]));
                SiteData siteData = JSON.parseObject(jobj.get(sourceNames[i]).toString(), SiteData.class);
                gasBaseDTO.setPicturePrefix(siteData.getPicturePrefix());
                logger.info("--" + siteData.getDateSourceName() + "--");
                DynamicDataSourceContextHolder.setDataSourceType(siteData.getDateSourceName());
                gasBaseDTO.setStart(startEndNums.get(i).get(0));
                gasBaseDTO.setEnd(startEndNums.get(i).get(1) - startEndNums.get(i).get(0));
                gasBaseDTO.setSdId(Integer.parseInt(sourceNames[i]));
                gasBaseDTO.setSiteName(siteData.getName());
                gasBaseDTO.setSitePhoto(siteData.getPhoto());

                List<Map<String, Object>> mainLPList = gasBaseMapper.findGasBaseList(gasBaseDTO);
                mainLPLs.addAll(mainLPList);
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        } else {
            List<SiteVO> userSites = siteMapper.findUserSites(gasBaseDTO.getUserId());
            StringBuffer stringBuffer = new StringBuffer();
            for (SiteVO siteVO : userSites) {
                gasBaseDTO.setSdId(siteVO.getSdId());
                String dataSourceName = "";
                String sdIdStr = siteVO.getSdId().toString();
                SiteData siteData = null;
                if (!IsEmptyUtils.isEmpty(jobj.get(sdIdStr))) {
                    siteData = JSON.parseObject(jobj.get(sdIdStr).toString(), SiteData.class);
                }
                gasBaseDTO.setPicturePrefix(siteData.getPicturePrefix());
                if (!IsEmptyUtils.isEmpty(siteData)) {
                    dataSourceName = siteData.getDateSourceName();
                }
                if (!IsEmptyUtils.isEmpty(dataSourceName)) {
                    if (IsEmptyUtils.isEmpty(stringBuffer)) {
                        stringBuffer.append(siteVO.getSdId());
                    } else {
                        stringBuffer.append("," + siteVO.getSdId());
                    }
                    logger.info("null sdIds...--" + dataSourceName + "----");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);
                    Integer totalStatus = gasBaseMapper.findGasBaseTotal(gasBaseDTO);
                    total = total + totalStatus;
                    totalAll.add(totalStatus);
                }
            }
            ArrayList<ArrayList<Integer>> startEndNums = MyStartEndUtil.getStartEndArray(totalAll, startNum, endNum);
            String[] sourceNames = stringBuffer.toString().split(",");
            for (int i = 0; i < startEndNums.size(); i++) {
                SiteData siteData = JSON.parseObject(jobj.get(sourceNames[i]).toString(), SiteData.class);
                logger.info("--" + siteData.getDateSourceName() + "--");
                gasBaseDTO.setPicturePrefix(siteData.getPicturePrefix());
                gasBaseDTO.setSdId(Integer.parseInt(sourceNames[i]));
                DynamicDataSourceContextHolder.setDataSourceType(siteData.getDateSourceName());
                gasBaseDTO.setStart(startEndNums.get(i).get(0));
                gasBaseDTO.setEnd(startEndNums.get(i).get(1) - startEndNums.get(i).get(0));
                gasBaseDTO.setSdId(Integer.parseInt(sourceNames[i]));
                gasBaseDTO.setSiteName(siteData.getName());
                gasBaseDTO.setSitePhoto(siteData.getPhoto());

                List<Map<String, Object>> mainLPList = gasBaseMapper.findGasBaseList(gasBaseDTO);
                mainLPLs.addAll(mainLPList);
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }
        resultBean.setSuccess(true);
        resultBean.setResult(mainLPLs);
        resultBean.setTotal(total);
        resultBean.setResultCode(IStatusMessage.SystemStatus.SUCCESS.getCode());
        resultBean.setMsg(IStatusMessage.SystemStatus.SUCCESS.getMessage());
        return resultBean;
    }


}
